export default class CMap<T = any> {
    obj: { [key: string]: T }

    constructor() {
        this.clear()
    }

    get(key: string | number) {
        return this.obj[key + ''] as T
    }

    has(key: string | number) {
        return this.get(key) != null
    }

    set(key: string | number, value: T) {
        this.obj[key + ''] = value
    }

    /**
     *  遍历，返回true时停止遍历
     * @param callback -回调value,key,index
     * @example
     * cmap.forEach((key,value,index)=>{
     *  console.log(value)
     *  return index === 0
     * })
     */
    forEach(callback: (key: string, value: T, index: number) => unknown) {
        let i: number = 0
        for (let key in this.obj) {
            if (callback(key, this.obj[key as any], i) === true) return
            i++
        }
    }

    /**
     * 获取key列表
     * @returns
     */
    keys() {
        return Object.keys(this.obj)
    }

    /**
     * 获取值列表
     * @returns
     */
    values() {
        return Object.values(this.obj)
    }

    /**
     * 移除key
     * @returns
     */
    remove(key: string) {
        this.obj[`${key}`] = undefined
        delete this.obj[`${key}`]
    }

    /**
     * 获取map大小
     * @returns
     */
    size() {
        return this.keys().length
    }

    /**
     * 清空map
     * @returns
     */
    clear() {
        this.obj = {}
    }

    /**
     * 转为json字符串
     * @returns
     */
    toJson() {
        return JSON.stringify(this.obj)
    }
}
